package com.star.ms.controller;

import com.star.ms.common.entity.RestResponse;
import com.star.ms.config.ShiroConfig;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSubjectFactory;
import org.apache.shiro.mgt.SubjectFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 * @Author: Uni
 * @Time: 2022/5/12
 * @TODO
 */
@Controller
public class DispatcherController {

    @GetMapping("/logout")
    public String exitLogin(HttpServletResponse response){
        // 清除 shiro的缓存
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated())
            subject.logout();
        response.addCookie(new Cookie("usercode", null));
        response.addCookie(new Cookie("password", null));
        return "login";
    };

    @GetMapping({"/index.html", "/"})
    public String toIndex(){
        return "login";
    }

    @GetMapping("/register.html")
    public String toRegister(){
        return "register";
    }

    @GetMapping("/retrieve.html")
    public String toRetrieve() {return "retrieve";}
    @GetMapping("/login.html")
    public String toTest(){return "login";}

    @GetMapping("/user-center.html")
    public ModelAndView toUserCenter(ModelAndView model, @RequestParam(required = false) String type){
        if(type != null)
            model.addObject("type", type);
        else
            model.addObject("type", "base");
        model.setViewName("user/user-center");
        return model;
    }
    @GetMapping("/product.html")
    public String toProduct(){
        return "product/detail";
    }
    @GetMapping("/admin")
    public String toDefaultAdmin(Model model){
        return toAdminUser(model, "dashboard");
    }
    @GetMapping("/admin/{type}")
    public String toAdminUser(Model model, @PathVariable String type){
        if(type != null) {
            Subject subject = SecurityUtils.getSubject();
            // 判断是否有权限访问
            if(!subject.isPermitted("admin:" + type))
                model.addAttribute("type", "noauth");
            else
                model.addAttribute("type", type);
        }
        return "admin/admin-center";
    }

    @GetMapping("/testAlipay")
    public String toTestAlipay() { return "testAlipay";}

    @GetMapping("/noauth")
    @ResponseBody
    public String toNoauth() {
        return "没有权限访问";
    }
}
